package org.chl.chapter02.controller;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
public class FileController {

	SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");

	@PostMapping("upload")
	public String upload(MultipartFile uploadFile, HttpServletRequest request) {
		String realPath = "E:/basedir/work/Tomcat/localhost/upload/";
		String format = sdf.format(new Date());
		String dir = realPath + format;
		System.out.println(dir);
		File folder = new File(dir);
		if (!folder.isDirectory()) {
			folder.mkdirs();
		}

		String oldName = uploadFile.getOriginalFilename();
		String newFileName = UUID.randomUUID().toString() + oldName.substring(oldName.indexOf("."));

		try {
			uploadFile.transferTo(new File(dir, newFileName));

			return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/upload/"
					+ format + "/" + newFileName;
		} catch (IllegalStateException | IOException e) {
			e.printStackTrace();
		}

		return "上传失败！";
	}

	@PostMapping("uploads")
	public String uploads(MultipartFile[] uploadFiles, HttpServletRequest request) {
		String realPath = "E:/basedir/work/Tomcat/localhost/upload/";
		String format = sdf.format(new Date());
		String dir = realPath + format;
		System.out.println(dir);
		File folder = new File(dir);
		if (!folder.isDirectory()) {
			folder.mkdirs();
		}

		StringBuilder res = new StringBuilder();

		try {
			for (MultipartFile uploadFile : uploadFiles) {
				String oldName = uploadFile.getOriginalFilename();
				String newFileName = UUID.randomUUID().toString() + oldName.substring(oldName.indexOf("."));

				uploadFile.transferTo(new File(dir, newFileName));
				res.append(request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
						+ "/upload/" + format + "/" + newFileName + "/n/r");
			}
			
			return res.toString();
		} catch (IllegalStateException | IOException e) {
			e.printStackTrace();
		}

		return "上传失败！";
	}
}
